import { defineStore } from 'pinia'
import { logoutApi, userInfoApi } from '@/api'
import router from '@/router'
import { ElMessage } from 'element-plus'
import { useChatStore } from './chat'
export const useUserStore = defineStore('user', () => {
    const user = ref<UserInfo>({} as UserInfo)
    const token = ref('')

    const userToken = computed(() => `Bearer ` + token.value)
    async function getUserInfo() {
        const { data } = await userInfoApi()
        user.value = data
        useChatStore().getChatroomList()
    }
    async function logout() {
        await logoutApi()
        clearToken()
        ElMessage.success('退出成功')
        router.push('/login')
    }
    function clearToken() {
        user.value = {} as UserInfo
        token.value = ''
    }

    return { user, token, userToken, getUserInfo, logout, clearToken }
}, {
    persist: [
        {
            pick: ['token'],
            storage: localStorage
        }
    ]
})
